package com.szly.phm.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.szly.phm.admin.aspectj.annotation.OperationLogAnnotation;
import com.szly.phm.admin.aspectj.enums.ModuleEnum;
import com.szly.phm.admin.aspectj.enums.OperationActionEnum;
import com.szly.phm.admin.utils.CustomResponse;
import com.szly.phm.admin.utils.ExportEasyExcelUtil;
import com.szly.phm.admin.utils.SecurityUtils;
import com.szly.phm.common.entity.dto.stu.ExportStudentDTO;
import com.szly.phm.common.entity.dto.stu.SynStudentDTO;
import com.szly.phm.common.entity.dto.system.SysMessagePageDTO;
import com.szly.phm.common.entity.dto.user.*;
import com.szly.phm.common.entity.po.*;
import com.szly.phm.common.entity.result.CodeStatusEnum;
import com.szly.phm.common.entity.result.PageResult;
import com.szly.phm.common.entity.result.RootResponse;
import com.szly.phm.common.entity.vo.AreaList;
import com.szly.phm.common.entity.vo.permissiom.PermissionTreeVO;
import com.szly.phm.common.entity.vo.sc.DeleteStudentDTO;
import com.szly.phm.common.entity.vo.sc.ExportStudentVO;
import com.szly.phm.common.entity.vo.user.UserPageVO;
import com.szly.phm.common.mapper.*;
import com.szly.phm.common.service.*;
import com.szly.phm.common.utils.HandleUtils;
import com.szly.phm.common.utils.SHA256Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

import static cn.hutool.poi.excel.cell.CellUtil.getCellValue;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-07-02
 */
@RestController
@Validated
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping("/pc/user")
@Api(tags = "用户管理")
public class SysUserController {
    private final ISysUserService userService;
    private final ISysRoleService roleService;
    private final ISysPermissionService permissionService;
    private final SysUserMapper sysUserMapper;
    private final ScTeachDataMapper scTeachDataMapper;
    private final ScStudentMapper scStudentMapper;
    private final ScClassMapper scClassMapper;
    private final ScMajorMapper scMajorMapper;
    private final SysRoleMapper sysRoleMapper;
    private final SysUserRoleMapper sysUserRoleMapper;
    private final RaServerAreaMapper raserverAreaMapper;
    private Map<String, String> createTeachDataDTO = new ConcurrentHashMap<String, String>();

    @ApiOperation(value = "查询消息")
//    @OperationLogAnnotation(getModuleName = ModuleEnum.PERMISSION,getOperationAction = OperationActionEnum.UPDATE)
    @GetMapping("/v1/sysMessages")
    @CustomResponse
    public RootResponse sysMessages(@Valid SysMessagePageDTO teachDataTypePageDTO) {
        var loginUser = SecurityUtils.getLoginUser();
        var userDTO = new LoginUserDTO();
        userDTO.setUsername(loginUser.getUsername());
        userDTO.setUserId(loginUser.getUserId());
        return userService.selectSysMessages(teachDataTypePageDTO, userDTO);
    }

    @ApiOperation(value = "查询未读消息数量")
//    @OperationLogAnnotation(getModuleName = ModuleEnum.PERMISSION,getOperationAction = OperationActionEnum.UPDATE)
    @GetMapping("/v1/sysMessagesCount")
    @CustomResponse
    public RootResponse sysMessagesNotCount() {
        var loginUser = SecurityUtils.getLoginUser();
        var userDTO = new LoginUserDTO();
        userDTO.setUsername(loginUser.getUsername());
        userDTO.setUserId(loginUser.getUserId());
        return userService.selectSysMessagesNotCount(userDTO);
    }

    @ApiOperation(value = "设置单个已读消息")
    @OperationLogAnnotation(getModuleName = ModuleEnum.PERMISSION, getOperationAction = OperationActionEnum.UPDATE)
    @GetMapping("/v1/sysMessagesSetRead")
    @CustomResponse
    public RootResponse sysMessagesSetRead(@NotBlank(message = "Id不能为空") @RequestParam(value = "id") String id) {
        var loginUser = SecurityUtils.getLoginUser();
        var userDTO = new LoginUserDTO();
        userDTO.setUsername(loginUser.getUsername());
        userDTO.setUserId(loginUser.getUserId());
        return userService.selectSysMessagesSetRead(userDTO, id);
    }

    @ApiOperation(value = "设置全部已读")
    @OperationLogAnnotation(getModuleName = ModuleEnum.PERMISSION, getOperationAction = OperationActionEnum.UPDATE)
    @GetMapping("/v1/sysMessagesSetAllRead")
    @CustomResponse
    public RootResponse sysMessagesSetRead() {
        var loginUser = SecurityUtils.getLoginUser();
        var userDTO = new LoginUserDTO();
        userDTO.setUsername(loginUser.getUsername());
        userDTO.setUserId(loginUser.getUserId());
        return userService.selectSysMessagesSetAllRead(userDTO);
    }

    @ApiOperation(value = "批量添加用户")
    @OperationLogAnnotation(getModuleName = ModuleEnum.STUDENT, getOperationAction = OperationActionEnum.SAVE)
    @PostMapping("/v1/importStudent")
    @CustomResponse
    public RootResponse importStudent(@RequestParam("file") MultipartFile file, HttpServletRequest request, @NotBlank(message = "Id不能为空") @RequestParam(value = "classId") String classId, @NotBlank(message = "区域不能为空") @RequestParam(value = "areaId") String areaId) throws IOException {
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名,比如图片的jpeg,png
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        if (!".xlsx".equals(suffixName) && !".xls".equals(suffixName)) {
            return RootResponse.error("请正确上传excel文件！");
        }
        List<ImportUsers> importDatas = new ArrayList<>();
        var date = new Date();
        var loginUser = SecurityUtils.getLoginUser();
        createTeachDataDTO.put(loginUser.getUsername(), "0");
        // 解析Excel数据
        if (".xls".equals(suffixName)) {
            HSSFRow row = null;
            HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet = wb.getSheetAt(0);
            // 验证开头
            row = sheet.getRow(0);
            if (row.getCell(0) != null) {
                row.getCell(0).setCellType(CellType.STRING);
            }
            if (row.getCell(1) != null) {
                row.getCell(1).setCellType(CellType.STRING);
            }
            if (row.getCell(0) == null || row.getCell(1) == null) {
                return RootResponse.error("请使用正确模板！");
            }
            if (!"学号*".equals(row.getCell(0).getStringCellValue()) || !"姓名*".equals(row.getCell(1).getStringCellValue())) {
                return RootResponse.error("请使用正确模板！");
            }
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
//获取每一行数据
                row = sheet.getRow(i);
                ImportUsers data = new ImportUsers();
                if (row.getCell(0) != null) {
                    row.getCell(0).setCellType(CellType.STRING);
                }
                if (row.getCell(1) != null) {
                    row.getCell(1).setCellType(CellType.STRING);
                }
                var userName = row.getCell(0) == null ? null : row.getCell(0).getStringCellValue();
                var name = row.getCell(1) == null ? null : row.getCell(1).getStringCellValue();
                if ("".equals(userName) || userName == null) {
                    return RootResponse.error("请填写学号或工号！");
                }
                if ("".equals(name) || name == null) {
                    return RootResponse.error("请填写姓名！");
                }
                if (sysUserMapper.selectUserByUserName(userName) != null || scStudentMapper.selectScStudentByUserName(userName).size() > 0) {
                    return RootResponse.error("学号或工号重复！");
                }
//                if(password!=null){
//                    if(password.length()<6||password.length()>20){
//                        return  RootResponse.error("长度必须6-20位！");
//                    }
//                    if(Pattern.matches(password, "^^(?![a-zA-z]+$)(?!\\\\d+$)(?![!@#$%^&*_-]+$)(?![a-zA-z\\\\d]+$)(?![a-zA-z!@#$%^&*_-]+$)(?![\\\\d!@#$%^&*_-]+$)[a-zA-Z\\\\d!@#$%^&*_-]+$")){
//                        return   RootResponse.error("必须同时包含数字、大小写字母、特殊字符！");
//                    }
//                }
                data.setUserName(userName);
                data.setName(name);
//                data.setGender(row.getCell(2)==null?null:row.getCell(2).getStringCellValue());
//                data.setPhone(row.getCell(3)==null?null:row.getCell(3).getStringCellValue());
//                data.setMailbox(row.getCell(4)==null?null:row.getCell(4).getStringCellValue());
                data.setClassId(classId);

//                data.setPassword(password);
                importDatas.add(data);
            }
        } else {
            XSSFRow row = null;
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
            XSSFSheet sheet = wb.getSheetAt(0);
            row = sheet.getRow(0);
            if (row.getCell(0) != null) {
                row.getCell(0).setCellType(CellType.STRING);
            }
            if (row.getCell(1) != null) {
                row.getCell(1).setCellType(CellType.STRING);
            }
            if (row.getCell(0) == null || row.getCell(1) == null) {
                return RootResponse.error("请使用正确模板！");
            }
            if (!"学号*".equals(row.getCell(0).getStringCellValue()) || !"姓名*".equals(row.getCell(1).getStringCellValue())) {
                return RootResponse.error("请使用正确模板！");
            }
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
//获取每一行数据
                row = sheet.getRow(i);
                if (row == null) {
                    break;
                }
                ImportUsers data = new ImportUsers();
                if (row.getCell(0) != null) {
                    row.getCell(0).setCellType(CellType.STRING);
                }
                if (row.getCell(1) != null) {
                    row.getCell(1).setCellType(CellType.STRING);
                }
//                if ( row.getCell(2)!=null){
//                    row.getCell(2).setCellType(CellType.STRING);
//                }
//                if ( row.getCell(3)!=null){
//                    row.getCell(3).setCellType(CellType.STRING);
//                }
//                if ( row.getCell(4)!=null){
//                    row.getCell(4).setCellType(CellType.STRING);
//                }
//                if ( row.getCell(5)!=null){
//                    row.getCell(5).setCellType(CellType.STRING);
//                }
                var userName = row.getCell(0) == null ? null : row.getCell(0).getStringCellValue();
                var name = row.getCell(1) == null ? null : row.getCell(1).getStringCellValue();
//                var password=  row.getCell(5)==null?null:row.getCell(5).getStringCellValue();
                if ("".equals(userName) || userName == null) {
                    return RootResponse.error("请填写学号或工号！");
                }
                if ("".equals(name) || name == null) {
                    return RootResponse.error("请填写姓名！");
                }
                if (sysUserMapper.selectUserByUserName(userName) != null || scStudentMapper.selectScStudentByUserName(userName).size() > 0) {
                    return RootResponse.error("学号或工号重复！");
                }
//                if(password!=null){
//                    if(password.length()<6||password.length()>20){
//                        return  RootResponse.error("长度必须6-20位！");
//                    }
//                    String PW_PATTERN = "^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)[a-zA-Z0-9\\W]{6,}$";
//                    if(!password.matches( PW_PATTERN)){
//                       return RootResponse.error("密码必须同时包含数字、大小写字母、特殊字符！");
//                    }
//                }
                data.setUserName(userName);
                data.setName(name);
//                data.setGender(row.getCell(2)==null?null:row.getCell(2).getStringCellValue());
//                data.setPhone(row.getCell(3)==null?null:row.getCell(3).getStringCellValue());
//                data.setMailbox(row.getCell(4)==null?null:row.getCell(4).getStringCellValue());
                data.setClassId(classId);
//                data.setPassword(password);
                importDatas.add(data);
            }
        }
        //根据页面index 获取sheet页


//循环sesheet页中数据从第二行开始，第一行是标题

        int total = importDatas.size();
        int i = 0;
        if (importDatas != null && importDatas.size() != 0) {
            var wrapper1 = new LambdaQueryWrapper<SysRole>();
            wrapper1.eq(SysRole::getIsSoftDelete, false);
            wrapper1.eq(SysRole::getRoleName, "学生");
            var sysRole1 = sysRoleMapper.selectOne(wrapper1);
            if (sysRole1 == null) {
                return RootResponse.error("系统不存在学生角色！");
            }
            for (ImportUsers importUser : importDatas) {
                SysUser sysUser = new SysUser();
                sysUser.setId(HandleUtils.UUID32());
                sysUser.setCreator(loginUser.getUsername());
                sysUser.setCreateDateTime(date);
                sysUser.setUsername(importUser.getUserName());
                var salt = HandleUtils.getRandomString(32);
                var str = new StringBuilder();
                str = str.append("123456").append(salt);
                var pSHA256 = SHA256Utils.SHA256(str.toString());
                sysUser.setPassword(pSHA256);
                sysUser.setSalt(salt);
//    sysUser.setMobile(importUser.getPhone());
//    sysUser.setMailbox(importUser.getMailbox());
                sysUser.setIsSoftDelete(false);
                sysUser.setRealName(importUser.getName());
                sysUser.setUserType("00");
                sysUser.setAreaId(areaId);
                sysUserMapper.insert(sysUser);
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setId(HandleUtils.UUID32());
                sysUserRole.setCreator(loginUser.getUsername());
                sysUserRole.setCreateDateTime(date);
                sysUserRole.setUserId(sysUser.getId());
                sysUserRole.setRoleId(sysRole1.getId());
                sysUserRoleMapper.insert(sysUserRole);
                var scStudent = new ScStudent();
                scStudent.setId(HandleUtils.UUID32());
                scStudent.setCreator(loginUser.getUsername());
                scStudent.setCreateDateTime(date);
                scStudent.setStudentId(importUser.getUserName());
                scStudent.setName(importUser.getName());
                scStudent.setIsSoftDelete(false);
                scStudent.setClassId(importUser.getClassId());
                scStudentMapper.insert(scStudent);
                i++;
                var j = (float) i / (float) total;
                if (j < 0.1) {
                    createTeachDataDTO.put(loginUser.getUsername(), Float.toString(j));
                }
                if (j < 0.2) {
                    createTeachDataDTO.put(loginUser.getUsername(), Float.toString(j));
                }
                if (j < 0.3) {
                    createTeachDataDTO.put(loginUser.getUsername(), Float.toString(j));
                }
                if (j < 0.4) {
                    createTeachDataDTO.put(loginUser.getUsername(), Float.toString(j));
                }
                if (j < 0.5) {
                    createTeachDataDTO.put(loginUser.getUsername(), Float.toString(j));
                }
                if (j < 0.6) {
                    createTeachDataDTO.put(loginUser.getUsername(), Float.toString(j));
                }
                if (j < 0.7) {
                    createTeachDataDTO.put(loginUser.getUsername(), Float.toString(j));
                }
                if (j < 0.8) {
                    createTeachDataDTO.put(loginUser.getUsername(), Float.toString(j));
                }
                if (j < 0.9) {
                    createTeachDataDTO.put(loginUser.getUsername(), Float.toString(j));
                }

            }

//            createTeachDataDTO.remove(loginUser.getUsername());
        }
        createTeachDataDTO.put(loginUser.getUsername(), "1");
        return RootResponse.success("导入成功！");
    }

    @ApiOperation(value = "批量添加用户进度")
    @GetMapping("/v1/importStatus")
    @CustomResponse
    public RootResponse importStatus() {
        var loginUser = SecurityUtils.getLoginUser();
        var userName = loginUser.getUsername();
        String value = null;
        for (Map.Entry<String, String> entry : createTeachDataDTO.entrySet()) {
            if (entry.getKey().equals(userName)) {
                value = entry.getValue();
            }
        }
        return RootResponse.success(Double.valueOf(value) * 100);
    }

    @ApiOperation(value = "批量同步学生")
    @PostMapping("/v1/synStudentStudent")
    @CustomResponse
    public RootResponse synStudent(@Valid @RequestBody SynStudentDTO importStudentDTO) throws IOException {
        var loginUser = SecurityUtils.getLoginUser();
        var date = new Date();
        var wrapper1 = new LambdaQueryWrapper<SysRole>();
        wrapper1.eq(SysRole::getIsSoftDelete, false);
        wrapper1.eq(SysRole::getRoleName, "学生");
        var sysRole1 = sysRoleMapper.selectOne(wrapper1);
        if (sysRole1 == null) {
            RootResponse.error("系统不存在学生角色！");
        }
        List<ScStudent> scStudents = scStudentMapper.selectSynStudent(importStudentDTO);
        scStudents.forEach(s -> {
            var sysUser1 = sysUserMapper.selectUserByUserName(s.getStudentId());
            if (sysUser1 == null) {
                SysUser sysUser = new SysUser();
                sysUser.setId(HandleUtils.UUID32());
                sysUser.setCreator(loginUser.getUsername());
                sysUser.setCreateDateTime(date);
                sysUser.setUsername(s.getStudentId());
                sysUser.setRealName(s.getName());
                sysUser.setAreaId(importStudentDTO.getAreaId());
                var salt = HandleUtils.getRandomString(32);
                var str = new StringBuilder();
                str = str.append("123456").append(salt);
                var pSHA256 = SHA256Utils.SHA256(str.toString());
                sysUser.setPassword(pSHA256);
                sysUser.setSalt(salt);
                sysUser.setIsSoftDelete(false);
                sysUser.setUserType("00");
                sysUserMapper.insert(sysUser);
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setId(HandleUtils.UUID32());
                sysUserRole.setCreator(loginUser.getUsername());
                sysUserRole.setCreateDateTime(date);
                sysUserRole.setUserId(sysUser.getId());
                sysUserRole.setRoleId(sysRole1.getId());
                sysUserRoleMapper.insert(sysUserRole);
            } else {
                sysUser1.setRealName(s.getName());
                sysUser1.setAreaId(importStudentDTO.getAreaId());
                sysUserMapper.updateById(sysUser1);
            }
        });
        return RootResponse.success();
    }

    @ApiOperation(value = "导出学生")
    @PostMapping("/v1/exportStudent")
    @CustomResponse
    public void exportStudent(@Valid @RequestBody ExportStudentDTO importStudentDTO, HttpServletResponse response) throws IOException {
        List<ExportStudentVO> selectExportUserDatas = scStudentMapper.selectExportUserData(importStudentDTO);
        String str = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String fileName = "学生数据" + str;
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        ExportEasyExcelUtil.writeWeb(response, fileName, selectExportUserDatas, ExportStudentVO.class);
    }

    @ApiOperation(value = "批量删除学生")
    @PostMapping("/v1/deleteStudent")
    @CustomResponse
    public RootResponse deleteStudent(@Valid @RequestBody DeleteStudentDTO importStudentDTO) throws IOException {
        if (importStudentDTO.getStudentIds() != null && importStudentDTO.getStudentIds().size() != 0) {
            List<String> xuehao = scStudentMapper.selectScStudentUserName(importStudentDTO.getStudentIds());
            var wrapper1 = new LambdaQueryWrapper<SysUser>();
            wrapper1.in(SysUser::getUsername, xuehao);
            var sysUser = new SysUser();
            sysUser.setIsSoftDelete(true);
            sysUserMapper.update(sysUser, wrapper1);
            //删除学生
            var wrapper = new LambdaQueryWrapper<ScStudent>();
            wrapper.in(ScStudent::getId, importStudentDTO.getStudentIds());
            var scStudent = new ScStudent();
            scStudent.setIsSoftDelete(true);
            scStudentMapper.update(scStudent, wrapper);
        }
        return RootResponse.success();
    }

    @ApiOperation(value = "批量删除用户")
    @PostMapping("/v1/deleteUsers")
    @CustomResponse
    public RootResponse deleteUsers(@Valid @RequestBody DeleteUserDTO importStudentDTO) throws IOException {
        if (importStudentDTO.getUserIds() != null && importStudentDTO.getUserIds().size() != 0) {
            var wrapper = new LambdaQueryWrapper<SysUser>();
            wrapper.in(SysUser::getId, importStudentDTO.getUserIds());
            var scStudent = new SysUser();
            scStudent.setIsSoftDelete(true);
            sysUserMapper.update(scStudent, wrapper);
            var wrapper1 = new LambdaQueryWrapper<SysUserRole>();
            wrapper1.in(SysUserRole::getUserId, importStudentDTO.getUserIds());
            var sysUserRole = new SysUserRole();
            sysUserRole.setIsSoftDelete(true);
            sysUserRoleMapper.update(sysUserRole, wrapper1);
        }
        return RootResponse.success();
    }

    @ApiOperation(value = "分页查询用户列表")
    @GetMapping("/v1/users")
    @CustomResponse
    public RootResponse<PageResult<UserPageVO>> queryUserPageV1(@Valid UserPageDTO pageDTO) {
        return userService.queryUserPage(pageDTO);
    }

    @ApiOperation(value = "根据用户id查询角色")
    @GetMapping("/v1/usersRoles")
    @CustomResponse
    public RootResponse queryUserPageV1(@NotBlank(message = "Id不能为空") @RequestParam(value = "userId") String userId) {
        return userService.queryUserRoles(userId);
    }

    @ApiOperation(value = "验证登录")
    @PostMapping("/v1/verificationUser")
    @CustomResponse
    public RootResponse<PageResult<UserPageVO>> queryUserLongin(@Valid VerificationUserDTO verificationUserDTO) {
        return userService.queryUserLongin(verificationUserDTO);
    }

    @ApiOperation(value = "添加用户")
    @OperationLogAnnotation(getModuleName = ModuleEnum.USER, getOperationAction = OperationActionEnum.SAVE)
    @PostMapping("/v1/users")
    @CustomResponse
    public RootResponse createUserV1(@Valid @RequestBody CreateUserDTO userDTO) {
        var loginUser = SecurityUtils.getLoginUser();
        var loginDTO = new LoginUserDTO();
        loginDTO.setUsername(loginUser.getUsername());
        return userService.createUser(userDTO, loginDTO);
    }

    @ApiOperation(value = "编辑用户")
    @OperationLogAnnotation(getModuleName = ModuleEnum.USER, getOperationAction = OperationActionEnum.UPDATE)
    @PutMapping("/v1/users")
    @CustomResponse
    public RootResponse updateRoleV1(@Valid @RequestBody UpdateUserDTO userDTO) {
        var loginUser = SecurityUtils.getLoginUser();
        var loginDTO = new LoginUserDTO();
        loginDTO.setUsername(loginUser.getUsername());
        return userService.updateUser(userDTO, loginDTO);
    }
//    @ApiOperation(value = "编辑用户头像或名字")
//    @OperationLogAnnotation(getModuleName = ModuleEnum.USER, getOperationAction = OperationActionEnum.UPDATE)
//    @PutMapping("/v1/updateHeaderOrName")
//    @PreAuthorize("hasAuthority('main-system-user') or hasAuthority('supperAdmin')")
//    public RootResponse updateHeaderName(@Valid @RequestBody UpdateUserHeaderDTO userDTO) {
//        var loginUser = SecurityUtils.getLoginUser();
//        var loginDTO = new LoginUserDTO();
//        loginDTO.setUsername(loginUser.getUsername());
//        loginDTO.setUserId(loginUser.getUserId());
//        return userService.updateHeaderName(userDTO, loginDTO);
//    }

    @ApiOperation(value = "删除用户")
    @OperationLogAnnotation(getModuleName = ModuleEnum.USER, getOperationAction = OperationActionEnum.DELETE)
    @ApiImplicitParam(name = "id", value = "用户Id", dataType = "String", required = true, dataTypeClass = String.class)
    @DeleteMapping("/v1/users")
    @CustomResponse
    public RootResponse deleteRoleV1(@NotBlank(message = "用户Id不能为空") @RequestParam(value = "id") String id) {
        var loginUser = SecurityUtils.getLoginUser();
        var loginDTO = new LoginUserDTO();
        loginDTO.setUsername(loginUser.getUsername());
        return userService.deleteUser(id, loginDTO);
    }

    @ApiOperation(value = "重置密码")
    @ApiImplicitParam(name = "id", value = "用户Id", dataType = "String", required = true, dataTypeClass = String.class)
    @GetMapping("/v1/users/reset")
    @CustomResponse
    public RootResponse resetPasswordV1(@NotBlank(message = "用户Id不能为空") String id) {
        var loginUser = SecurityUtils.getLoginUser();
        var loginDTO = new LoginUserDTO();
        loginDTO.setUsername(loginUser.getUsername());
        return userService.resetPassword(id, loginDTO);
    }

    @ApiOperation(value = "给用户分配角色")
    @OperationLogAnnotation(getModuleName = ModuleEnum.ROLE, getOperationAction = OperationActionEnum.SAVE)
    @PostMapping("/v1/users/roles")
    @CustomResponse
    public RootResponse createUsersRoles(@Valid @RequestBody UserRoleDTO roleDTO) {
        var loginUser = SecurityUtils.getLoginUser();
        var userDTO = new LoginUserDTO();
        userDTO.setUsername(loginUser.getUsername());
        return userService.createUsersRoles(roleDTO, userDTO);
    }

    @ApiOperation(value = "修改密码")
    @OperationLogAnnotation(getModuleName = ModuleEnum.USER, getOperationAction = OperationActionEnum.ROLE_ASSIGN_PERMISSION)
    @PutMapping("/v1/users/update")
    @CustomResponse
    public RootResponse updatePasswordV1(@Valid @RequestBody UpdatePasswordDTO passwordDTO) {
        var loginUser = SecurityUtils.getLoginUser();
        var loginDTO = new LoginUserDTO();
        loginDTO.setUserId(loginUser.getUserId());
        loginDTO.setUsername(loginUser.getUsername());
        return userService.updatePassword(passwordDTO, loginDTO);
    }


    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/v1/users/userInfo")
    @CustomResponse
    public RootResponse getUserInfo(HttpServletRequest request) {
        var loginUser = SecurityUtils.getLoginUser();
        //查询用户
        var user = userService.getById(loginUser.getUserId());
        if (user == null || user.getIsSoftDelete()) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
//        loginUser.setHeaderId(user.getHeaderId());
//        loginUser.setAreaId(user.getArea().get(0).getAreaId());
        //查询角色
        var roles = roleService.queryRolesByUserId(loginUser.getUserId());
        loginUser.setRoles(roles);
        //查询权限
        var roleIds = new ArrayList<String>();
        //是否超级管理员
        AtomicBoolean supperAdmin = new AtomicBoolean(false);
        if (HandleUtils.ListIsNotNull(roles)) {
            loginUser.setRoleId(roles.get(0).getId());
            loginUser.setRoleName(roles.get(0).getRoleName());
            roles.forEach(r -> {
                roleIds.add(r.getId());
                if ("超级管理员".equals(r.getRoleName())) {
                    supperAdmin.set(true);
                }
            });
        }
        var permissions = permissionService.queryPermissionsByRoleIds1(roleIds, supperAdmin);
        loginUser.setUserPermissions(permissions);
        //授权
        var auth = new ArrayList<SimpleGrantedAuthority>();
        for (PermissionTreeVO lp : permissions) {
            auth.add(new SimpleGrantedAuthority("ROLE_" + lp.getRouter()));
        }
        loginUser.setAuthorities(auth);
        loginUser.setPassword(null);
        loginUser.setMailbox(user.getMailbox());
        loginUser.setCertificatesId(user.getCertificatesId());
        loginUser.setJobName(user.getJobName());
        loginUser.setRealName(user.getRealName());
        loginUser.setRemarks(user.getRemarks());
        AreaList areaList = new AreaList();
        var raserverArea = raserverAreaMapper.selectById(user.getAreaId());
        areaList.setAreaId(user.getAreaId());
        areaList.setAreaName(raserverArea==null ? "":raserverArea.getName());
        ArrayList<AreaList> lists = new ArrayList<>();
        lists.add(areaList);
        loginUser.setArea(lists);
        return RootResponse.success(loginUser);
    }

}

